package comptadub

import java.io.File
import java.text.SimpleDateFormat

class NoteDeFraisController {

	def grailsApplication
	
    def exportService
    def membreService
    def compteService

    static allowedMethods = [save: "POST", update: "POST"]
    static authorizedImageContentType = [ 'image/jpeg' :'jpg', 'image/gif' :'gif', 'image/png' :'png']

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {
        flash.objet = params.objet
        flash.membre = params.membre

        if (!params.max) params.max = 10
        if (!params.sort) params.sort = "id"
        if (!params.order) params.order = "desc"
        if (!flash.membre) flash.membre = session.idMembre.toString()
        
        def query = {
            and {
                if(flash.objet) {
                    like("objet", '%' + flash.objet + '%')
                }

                if (flash.membre != '0') {
                    def selMembre = Membre.get(flash.membre.toInteger())
                    eq("membre", selMembre)
                }
            }
        }

        def criteria = NoteDeFrais.createCriteria()
        def results = criteria.list(params, query)

        [ noteDeFraisInstanceList: results ]
    }

    def export = {
        flash.objet = params.objet
        flash.membre = params.membre
        params.max = null
        params.offset = null

        if (!params.sort) params.sort = "id"
        if (!params.order) params.order = "desc"

        def query = {
            and {
                if(flash.objet) {
                    like("objet", '%' + flash.objet + '%')
                }

                if (flash.membre != '0') {
                    def selMembre = Membre.get(flash.membre.toInteger())
                    eq("membre", selMembre)
                }
            }
        }

        def criteria = NoteDeFrais.createCriteria()
        def results = criteria.list(params, query)

        if(params?.format && params.format != "html")
        {
            response.contentType = grailsApplication.config.grails.mime.types[params.format]
            response.setHeader("Content-disposition", "attachment; filename=note_de_frais.${params.extension}")
            List fields = ["membre.nom", "date", "credit", "numeroFacture", "description", "objet", "commentaire"]
            Map labels = ["membre.nom": "membre", "credit": "montant"]
            exportService.export(params.format, response.outputStream, results, fields, labels, [:], [:])
        }
    }

    def create = {
        def noteDeFraisInstance = new NoteDeFrais()
        noteDeFraisInstance.membre = Membre.get(session.idMembre.toString())
        noteDeFraisInstance.properties = params
        return [noteDeFraisInstance: noteDeFraisInstance]
    }

    def save = {
        def noteDeFraisInstance = new NoteDeFrais(params)
        def fichier = request.getFile('justificatif')

        /*def fichier = request.getFile('justificatif.data')

        if (!fichier.empty) {
            noteDeFraisInstance.nomJustificatif = fichier.originalFilename
        }*/

        compteService.definirObjet(noteDeFraisInstance)

        // sauvegarde de l'image
        def imageSaved = saveImageFile(fichier, "justificatif")

        if (imageSaved) {
            noteDeFraisInstance.pathJustificatif = imageSaved
        } else {
            flash.message = 'Mauvais format d\'image. Formats acceptés : jpeg, gif et png'
            render(view: "create", model: [noteDeFraisInstance: noteDeFraisInstance])
        }

        if (noteDeFraisInstance.save(flush: true)) {
            flash.message = "${message(code: 'noteDeFrais.created.message')}"
            membreService.calculerSolde(noteDeFraisInstance.membre?.id)
            redirect(action: "show", id: noteDeFraisInstance.id)
        }
        else {
            render(view: "create", model: [noteDeFraisInstance: noteDeFraisInstance])
        }
    }

    def show = {
        def noteDeFraisInstance = NoteDeFrais.get(params.id)
        if (!noteDeFraisInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'noteDeFraisInstance.label', default: 'NoteDeFrais'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [noteDeFraisInstance: noteDeFraisInstance]
        }
    }

    def edit = {
        def noteDeFraisInstance = NoteDeFrais.get(params.id)
        if (!noteDeFraisInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'noteDeFraisInstance.label', default: 'NoteDeFrais'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [noteDeFraisInstance: noteDeFraisInstance]
        }
    }

    def update = {
        def noteDeFraisInstance = NoteDeFrais.get(params.id)

        /*if (params.justificatif.data) {
            def justificatif = request.getFile('justificatif.data')
            noteDeFraisInstance.nomJustificatif = justificatif.originalFilename
        }*/

        if (noteDeFraisInstance) {

            if (params.version) {
                def version = params.version.toLong()
                if (noteDeFraisInstance.version > version) {
                    noteDeFraisInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'noteDeFraisInstance.label', default: 'NoteDeFrais')] as Object[], "Another user has updated this NoteDeFrais while you were editing")
                    render(view: "edit", model: [noteDeFraisInstance: noteDeFraisInstance])
                    return
                }
            }

            // sauvegarde de l'image
            removeImageFile(noteDeFraisInstance.pathJustificatif)
            def imageSaved = saveImageFile(request.getFile('justificatif'), "justificatif")

            if (imageSaved) {
                noteDeFraisInstance.pathJustificatif = imageSaved
            } else {
                flash.message = 'Mauvais format d\'image. Formats acceptés : jpeg, gif et png'
                render(view: "edit", model: [noteDeFraisInstance: noteDeFraisInstance])
            }
            
            noteDeFraisInstance.properties = params
            compteService.definirObjet(noteDeFraisInstance)

            if (!noteDeFraisInstance.hasErrors() && noteDeFraisInstance.save(flush: true)) {
                flash.message = "${message(code: 'noteDeFrais.updated.message')}"
                membreService.calculerSolde(noteDeFraisInstance.membre?.id)
                redirect(action: "show", id: noteDeFraisInstance.id)
            }
            else {
                render(view: "edit", model: [noteDeFraisInstance: noteDeFraisInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'noteDeFraisInstance.label', default: 'NoteDeFrais'), params.id])}"
            redirect(action: "list")
        }
    }

    def delete = {
        def noteDeFraisInstance = NoteDeFrais.get(params.id)
        if (noteDeFraisInstance) {
            try {
                removeImageFile(noteDeFraisInstance.pathJustificatif)
                noteDeFraisInstance.delete(flush: true)
                flash.message = "${message(code: 'noteDeFrais.deleted.message')}"
                membreService.calculerSolde(noteDeFraisInstance.membre?.id)
                redirect(action: "list")
            }
            catch (org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "${message(code: 'default.not.deleted.message', args: [message(code: 'noteDeFraisInstance.label', default: 'NoteDeFrais'), params.id])}"
                redirect(action: "show", id: params.id)
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'noteDeFraisInstance.label', default: 'NoteDeFrais'), params.id])}"
            redirect(action: "list")
        }
    }

    def image = {
        String filename = params.id
        def path = grailsAttributes.getApplicationContext().getResource("file").getFile().toString() + File.separatorChar + filename

        def file = new File(path)
        if (file.exists()) {
            response.setContentType("application/octet-stream")
            response.setHeader("Content-Disposition", "attachment; filename=${filename}")
            response.setContentLength(file.readBytes().size())
            response.getOutputStream() << file.readBytes()
        }
    }

    def saveImageFile(fichier, name) {
        
        if (!fichier.empty) {

            FileNameMap fileNameMap = URLConnection.getFileNameMap();
            def contentType = fileNameMap.getContentTypeFor(fichier.originalFilename)
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss_SSS")

            // checking if file to save has authorized mime type
            if ( authorizedImageContentType.keySet().contains(contentType) ) {

                name = dateFormat.format(new Date()) + "_" + name + "." + authorizedImageContentType[contentType]
                def path = grailsAttributes.getApplicationContext().getResource("file").getFile().toString() + File.separatorChar + name
                /*def thumbPath = grailsAttributes.getApplicationContext().getResource("file/thumb").getFile().toString() + File.separatorChar + name

                def imageTool = new ImageTool()

                imageTool.load(fichier)
                imageTool.thumbnail(640)
                imageTool.writeResult(imagePath, "JPEG")
                imageTool.swapSource()
                imageTool.thumbnail(40)
                imageTool.square()
                imageTool.writeResult(thumbPath, "JPEG")*/

                fichier.transferTo(new File(path))

                return name
            }
        }
    }

    def removeImageFile(name) {
        def path = grailsAttributes.getApplicationContext().getResource("file").getFile().toString() + File.separatorChar + name
        File storedImage = new File(path)

        if (storedImage.exists()) {
            return storedImage.delete()
        }
    }
}
